package com.yonyou.ucf.mdf.app.controller.isv;


import com.yonyou.ucf.mdd.ext.base.BaseController;
import com.yonyou.ucf.mdd.ext.core.AppContext;
import com.yonyou.ucf.mdf.app.common.ResultMessage;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Properties;

@Slf4j
@RestController
@RequestMapping("/openapi")
public class OpenAppKeyInfoController extends BaseController {


    @GetMapping("/appcode")
    public void getAppCode(@RequestParam(value = "domain", required = true) String domain, HttpServletRequest request,
                           HttpServletResponse response) {
        Properties appConfig = AppContext.getAppConfig();
        if (domain.equals(appConfig.getProperty("spring.application.name"))) {
            HashMap<String, String> resultMap = new HashMap<>();
            resultMap.put("appCode", appConfig.getProperty("ucf.mdd.open-api.app-code"));
            resultMap.put("applicationName", domain);
            renderJson(response, ResultMessage.data(resultMap));
        } else {
            renderJson(response, ResultMessage.error("获取appCode失败，domain非法"));
        }
    }

    @PostMapping("/update/appinfo")
    public void updateAppInfo(@RequestBody HashMap<String, String> requestBody,
                              HttpServletRequest request,
                              HttpServletResponse response) {
        Properties appConfig = AppContext.getAppConfig();
        String domain = requestBody.get("domain");
        String appCode = requestBody.get("appCode");
        String appKey = requestBody.get("appKey");
        String appSecret = requestBody.get("appSecret");
        if (StringUtils.isNotBlank(domain)
                && domain.equals(appConfig.getProperty("spring.application.name"))
                && StringUtils.isNotBlank(appCode)
                && appCode.equals(appConfig.getProperty("ucf.mdd.open-api.app-code"))) {
            appConfig.setProperty("ucf.mdd.open-api.app-key", appKey);
            appConfig.setProperty("ucf.mdd.open-api.app-secret", appSecret);
            renderJson(response, ResultMessage.success("更新appkey成功"));
        }
        renderJson(response, ResultMessage.error("更新appkey失败"));
    }

}
